package com.redis.springbootredis.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;

import java.time.Duration;

/**
 * @author
 * @create 2020-10-30 17:59
 * 统一设置的序列化器默认的缓存时间是永久，可以添加entryTtl(Duration.ofSeconds(秒数))来统一控制生命周期
 * 重写RedisCacheConfiguration配置类，实现自定义序列化器的效果
 */

@Configuration
public class RedisCacheConfig {

    @Bean
    public RedisCacheConfiguration redisCacheConfiguration(){
        RedisCacheConfiguration redisCacheConfiguration =
                RedisCacheConfiguration.defaultCacheConfig();

        redisCacheConfiguration = redisCacheConfiguration
                //设置键的设值类型
                .serializeKeysWith(
                RedisSerializationContext.SerializationPair.fromSerializer(RedisSerializer.string()))
                //设置值的序列化方式
                .serializeValuesWith(
                        RedisSerializationContext.SerializationPair.fromSerializer(RedisSerializer.json()))
                //统一添加过期时间
                .entryTtl(Duration.ofSeconds(6666));
        return redisCacheConfiguration;
    }
}
